package com.qf;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sunyamei
 * @version V1.0
 * @Project javase2203
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/7/27 11:03
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    @PostMapping("/create")
    public  Object create(@RequestParam("file")MultipartFile file)throws Exception{

        //1:获取文件上传的文件名
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)){
            throw  new RuntimeException("上传的文件为空,不允许上传");
        }
        //2:获取文件扩展名
        String ext = filename.substring(filename.lastIndexOf("."));
        //3:获取文件大小
        long size = file.getSize();
        //4:获取文件内容
        byte[] content = file.getBytes();
        //5:调用service上传
        DtsStorage storage = storageService.add(filename, ext, size, content);
        return ResponseUtil.ok(storage);


    }

    /**
     *      list?page=1&limit=20&sort=add_time&order=desc
     * @param page  当前页
     * @param limit 每页查询条数
     * @param sort  排序字段名
     * @param order 排序方式
     * @param key   根据key查询
     * @param name  根据名字查询
     * @return
     */
    @GetMapping("/list")
    public  Object list(Integer page,Integer limit,String sort,String order,String key,String name){

        IPage<DtsStorage> iPage = storageService.queryByPage(page, limit, sort, order, key, name);

        //查询总条数
        long total = iPage.getTotal();

        //查询到当前页数
        List<DtsStorage> list = iPage.getRecords();

        Map<String, Object> data = new HashMap<>();

        data.put("total", total);
        data.put("items", list);

        return  ResponseUtil.ok(data);
    }


}
